require "yaml"

puts '[info] begin to convert viewlog from string to integer...'
exit 0 if ARGV[0] == nil
workingDir = ARGV[0]
inputFile = ARGV[1]
outputFile = "#{inputFile}_int"

userIdMap = Hash.new
programIdMap = Hash.new
userId = 1
programId = 1
puts "[info] begin to convert file #{workingDir}/#{inputFile}..."
begin
  inFile = File.open("#{workingDir}/#{inputFile}", 'r')
  outFile = File.open("#{workingDir}/#{outputFile}", 'w')
  inFile.each_line { |line|
    lineArr = line.split("\t")
    if userIdMap[lineArr[0]] == nil
      userIdMap[lineArr[0]] = userId
      userId += 1
    end
    if programIdMap[lineArr[1]] == nil
      programIdMap[lineArr[1]] = programId
      programId += 1
    end
    outFile.write("#{userIdMap[lineArr[0]].to_s}\t#{programIdMap[lineArr[1]].to_s}\t#{lineArr[2].to_s}\t#{lineArr[3].to_s}") if lineArr[0]!=nil && lineArr[1]!=nil && lineArr[2]!=nil && lineArr[3]!=nil
  }
ensure
  inFile.close if inFile != nil
  outFile.close  if outFile != nil
end
puts '[info] end of converting viewlog from string to integer'

puts '[info] begin to serialize HashMaps...'
userIdFile = File.open("#{workingDir}/yaml/userIdMap", 'w')
userIdFile.write(YAML::dump(userIdMap))
programIdFile = File.open("#{workingDir}/yaml/programIdMap", 'w')
programIdFile.write(YAML::dump(programIdMap))

puts '[info] end of serializing HashMaps...'
